import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import routersConfig from "./config";
import store from "../store/index";
const routes = [
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login.vue"),
  },
  {
    path: "/mainBox",
    name: "mainBox",
    component: () => import("../views/mainBox.vue"),
  },
  // mainBox的嵌套路由，后面根据权限动态添加
];

const router = createRouter({
  history: createWebHashHistory(),
  routes: routes,
});
// 每次路由跳转之前
router.beforeEach((to, form, next) => {
  if (to.name === "login") {
    next();
  } else {
    // 如果已经登陆就可以进行next
    // 如果未登录重定向到login
    if (!sessionStorage.getItem("token")) {
      next({
        path: "/login",
      });
    } else {
      if (!store.state.isGetterRouter) {
        ConfigRouter();
        next({
          path: to.fullPath,
        });
      } else {
        next();
      }
    }
  }
});
const ConfigRouter = () => {
  routersConfig.forEach((item) => {
    router.addRoute("mainBox", item);
  });
  // 改变isGetterRouter 为true
  store.commit("changeGetterRouter", true);
};

export default router;
